import base from "./base.controller";

import md5 from "md5";
import fs from "fs-promise";

export default class extends base {
    async _initialize() {
        await super._initialize();
        const {code, message} = await super.checkAccessPermission('manage_account', '用户不能管理系统账户信息');
    }

    async index() {
        await this.render('admin/administrator/index', {
            status: [{key: '0', title: '关闭'}, {key: '1', title: '开启'}]
        });
    }

    async table() {

        const p = this.query.page || 1;

        const post = this.post;
        const id = post.id.trim();
        const status = post.status.trim();
        const keywords = post.keywords.trim();

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (keywords !== "") {
            queryParams = {
                $or: [
                    {username: {$regex: keywords, $options: "$i"}},
                    {email: {$regex: keywords, $options: "$i"}},
                    {mobile: {$regex: keywords, $options: "$i"}}
                ]
            }
        }

        //等值查询
        if (status !== "") {
            queryParams = Object.assign(queryParams, {status: status});
        }

        //id属性要单独查找,不支持正则表达式
        if (id !== "") {
            try {
                queryParams = {
                    _id: koahub.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.error('没找到符合条件的记录');
                return;
            }
        }


        this.logger.debug(`search queryParams:${JSON.stringify(queryParams)}`);


        /**
         * 获取对模型的引用，如果模型不存在则创建模型并调用初始化操作增加测试数据
         */
        let Model = this.model('admin/Administrator');
        const pageSize = await this.common.config('LIST_ROWS');

        let administrator = await Model.findPage({
            page: p,
            pageSize: pageSize
        }, '', queryParams, {}, {_id: 'asc'}, function (error, results) {
            // console.log(results);
        });

        await this.render('admin/administrator/table', {
            records: administrator.data,
            pager: this.common.ajaxPage(p, administrator.pagination.rowCount, administrator.pagination.pageSize)
        });
    }

    async disable() {
        const id = this.post.id || "";
        const ids = id.split(',');
        let Model = this.model('admin/Administrator');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 0}).exec();
        }
        this.success('禁用用户成功');

    }

    async enable() {
        const id = this.post.id || "";
        const ids = id.split(',');
        let Model = this.model('admin/Administrator');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 1}).exec();
            //this.changeModelField('admin/User', i, 'status', 1);
        }
        this.success('开启用户成功');
    }

    async delete() {
        const id = this.post.id || "";
        const ids = id.split(',');
        let Model = this.model('admin/Administrator');
        for (const i of ids) {
            // await Model.findByIdAndRemove(i).exec();
            await Model.findUserByIdAndRemove(i);//删除关联数据
        }
        this.success('/admin/administrator/index', '删除用户成功');
    }

    async add() {

        if (this.isPost()) {

            const administrator = this.post;

            if (administrator.password) {
                administrator.password = md5(administrator.password);
            } else {
                delete administrator.password;
            }

            this.model('admin/Administrator').saveOrUpdate(administrator);

            this.json('/admin/administrator/index', '保存成功');

        } else {

            if (this.query.id) {
                const administrator = await this.model('admin/Administrator').findOne({_id: this.query.id}).exec();
                await this.render('admin/administrator/add', {administrator: administrator});
            } else {
                await this.render('admin/administrator/add');
            }
        }
    }
}